package it.appcatalogobase;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.text.Html;
import android.util.Log;
import android.widget.Toast;

public class MyAsyncTask extends AsyncTask<Void, Void, Void> {

	private ProgressDialog progressDialog;
	private InputStream inputStream = null;
	private InputStream inputStream2 = null;
	private InputStream inputStreamDS = null;
	private InputStream inputStreamDEL = null;
	private InputStream inputStreamDET = null;
	private HashMap<String, String> colori = new HashMap<String, String>();

	public InputStream getInputStreamDET() {
		return inputStreamDET;
	}

	public void setInputStreamDET(InputStream inputStreamDET) {
		this.inputStreamDET = inputStreamDET;
	}

	public InputStream getInputStreamDEL() {
		return inputStreamDEL;
	}

	public void setInputStreamDEL(InputStream inputStreamDEL) {
		this.inputStreamDEL = inputStreamDEL;
	}

	public InputStream getInputStreamDS() {
		return inputStreamDS;
	}

	public void setInputStreamDS(InputStream inputStreamDS) {
		this.inputStreamDS = inputStreamDS;
	}

	public InputStream getInputStreamCS() {
		return inputStreamCS;
	}

	public void setInputStreamCS(InputStream inputStreamCS) {
		this.inputStreamCS = inputStreamCS;
	}

	private InputStream inputStreamCS = null;
	private String result = "";
	private String result2 = "";
	private String resultDS = "";
	private String resultCS = "";
	private String resultDEL = "";
	private String resultDET = "";

	public String getResultDET() {
		return resultDET;
	}

	public void setResultDET(String resultDET) {
		this.resultDET = resultDET;
	}

	public String getResultDEL() {
		return resultDEL;
	}

	public void setResultDEL(String resultDEL) {
		this.resultDEL = resultDEL;
	}

	private Activity a;
	private String url;
	private NetworkInfo intC;
	private Properties properties;

	public InputStream getInputStream2() {
		return inputStream2;
	}

	public void setInputStream2(InputStream inputStream2) {
		this.inputStream2 = inputStream2;
	}

	public String getResult2() {
		return result2;
	}

	public void setResult2(String result2) {
		this.result2 = result2;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public NetworkInfo getIntC() {
		return intC;
	}

	public void setIntC(NetworkInfo intC) {
		this.intC = intC;
	}

	public ProgressDialog getProgressDialog() {
		return progressDialog;
	}

	public void setProgressDialog(ProgressDialog progressDialog) {
		this.progressDialog = progressDialog;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public Activity getA() {
		return a;
	}

	public void setA(Activity a) {
		this.a = a;
	}

	public MyAsyncTask() {

	}

	public MyAsyncTask(String url, Activity a) {
		this.a = a;
		this.url = url;
		this.progressDialog = new ProgressDialog(a);
		this.properties = new Properties();

	}

	protected void onPreExecute() {
		a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
		DataAppPersistence dataPer = (DataAppPersistence) a.getApplication();
		if (dataPer.isStarted())
			progressDialog.setMessage("...Sincronizzo il catalogo...potrebbe richiedere qualche minuto");
		else
			progressDialog.setMessage("...Verifico gli aggiornamenti...potrebbe richiedere qualche minuto");
		progressDialog.setCancelable(false);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.show();
		progressDialog.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface arg0) {
				MyAsyncTask.this.cancel(true);
			}
		});
	}

	@Override
	protected Void doInBackground(Void... params) {
		AssetManager assetManager = a.getAssets();
		InputStream inputStream = null;
		try {
			inputStream = assetManager.open("config.properties");
			properties.load(inputStream);
		} catch (IOException e5) {
			// TODO Auto-generated catch block
			e5.printStackTrace();
		}

		ConnectivityManager conMgr = (ConnectivityManager) a.getSystemService(a.CONNECTIVITY_SERVICE);
		intC = conMgr.getActiveNetworkInfo();

		// String url_select = "http://yoururlhere.com";

		// ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
		if (intC != null && intC.isConnected() && intC.isAvailable()) {
			DataAppPersistence dataPer = (DataAppPersistence) a.getApplication();
			HttpClient httpClient = new DefaultHttpClient();
			HttpClient httpClient2 = new DefaultHttpClient();
			HttpClient httpClientDS = new DefaultHttpClient();
			HttpClient httpClientCS = new DefaultHttpClient();
			HttpClient httpClientDEL = new DefaultHttpClient();
			HttpClient httpClientDET = new DefaultHttpClient();
			// ArrayList<NameValuePair> nameValuePairs = new
			// ArrayList<NameValuePair>();
			// nameValuePairs.add(new BasicNameValuePair("year","1980"));
			HttpGet httpGet = new HttpGet(properties.getProperty("indirizzoCat"));
			// httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpGet httpGet2 = new HttpGet(properties.getProperty("indirizzoPro"));
			HttpGet httpGetDS = new HttpGet(properties.getProperty("indirizzoDoveSiamo"));
			HttpGet httpGetCS = new HttpGet(properties.getProperty("indirizzoChiSiamo"));
			HttpGet httpGetDEL = new HttpGet(properties.getProperty("indirizzoDelete"));
			HttpGet httpGetDET = new HttpGet(properties.getProperty("indirizzoDettaglio"));
			HttpResponse httpResponse;
			try {
				httpResponse = httpClient.execute(httpGet);
				HttpResponse httpResponse2 = httpClient2.execute(httpGet2);
				HttpResponse httpResponseDS = httpClientDS.execute(httpGetDS);
				HttpResponse httpResponseCS = httpClientCS.execute(httpGetCS);
				HttpResponse httpResponseDEL = httpClientDEL.execute(httpGetDEL);
				HttpResponse httpResponseDET = httpClientDET.execute(httpGetDET);
				Log.i("JSON", httpResponse.getStatusLine().toString());
				Log.i("JSON", httpResponse2.getStatusLine().toString());
				Log.i("JSON", httpResponseDS.getStatusLine().toString());
				Log.i("JSON", httpResponseCS.getStatusLine().toString());
				Log.i("JSON", httpResponseDEL.getStatusLine().toString());
				Log.i("JSON", httpResponseDET.getStatusLine().toString());
				HttpEntity httpEntity = httpResponse.getEntity();
				HttpEntity httpEntity2 = httpResponse2.getEntity();
				HttpEntity httpEntityDS = httpResponseDS.getEntity();
				HttpEntity httpEntityCS = httpResponseCS.getEntity();
				HttpEntity httpEntityDEL = httpResponseDEL.getEntity();
				HttpEntity httpEntityDET = httpResponseDET.getEntity();
				inputStream = httpEntity.getContent();
				inputStream2 = httpEntity2.getContent();
				inputStreamDS = httpEntityDS.getContent();
				inputStreamCS = httpEntityCS.getContent();
				inputStreamDEL = httpEntityDEL.getContent();
				inputStreamDET = httpEntityDET.getContent();
				try {
					BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
					StringBuilder sBuilder = new StringBuilder();

					String line = null;
					while ((line = bReader.readLine()) != null) {
						if (!line.equals("null"))
							sBuilder.append(line + "\n");
					}

					inputStream.close();
					result = sBuilder.toString();

					BufferedReader bReader2 = new BufferedReader(new InputStreamReader(inputStream2, "iso-8859-1"), 8);
					StringBuilder sBuilder2 = new StringBuilder();

					String line2 = null;
					while ((line2 = bReader2.readLine()) != null) {
						if (!line2.equals("null"))
							sBuilder2.append(line2 + "\n");
					}

					inputStream2.close();
					result2 = sBuilder2.toString();

					BufferedReader bReaderDS = new BufferedReader(new InputStreamReader(inputStreamDS, "iso-8859-1"), 8);
					StringBuilder sBuilderDS = new StringBuilder();

					String lineDS = null;
					while ((lineDS = bReaderDS.readLine()) != null) {
						if (!lineDS.equals("null"))
							sBuilderDS.append(lineDS + "\n");
					}

					inputStreamDS.close();
					resultDS = sBuilderDS.toString();

					BufferedReader bReaderCS = new BufferedReader(new InputStreamReader(inputStreamCS, "iso-8859-1"), 8);
					StringBuilder sBuilderCS = new StringBuilder();

					String lineCS = null;
					while ((lineCS = bReaderCS.readLine()) != null) {
						if (!lineCS.equals("null"))
							sBuilderCS.append(lineCS + "\n");
					}

					inputStreamCS.close();
					resultCS = sBuilderCS.toString();

					BufferedReader bReaderDEL = new BufferedReader(new InputStreamReader(inputStreamDEL, "iso-8859-1"), 8);
					StringBuilder sBuilderDEL = new StringBuilder();

					String lineDEL = null;
					while ((lineDEL = bReaderDEL.readLine()) != null) {
						if (!lineDEL.equals("null"))
							sBuilderDEL.append(lineDEL + "\n");
					}

					inputStreamDEL.close();
					resultDEL = sBuilderDEL.toString();

					BufferedReader bReaderDET = new BufferedReader(new InputStreamReader(inputStreamDET, "iso-8859-1"), 8);
					StringBuilder sBuilderDET = new StringBuilder();

					String lineDET = null;
					while ((lineDET = bReaderDET.readLine()) != null) {
						if (!lineDET.equals("null"))
							sBuilderDET.append(lineDET + "\n");
					}

					inputStreamDET.close();
					resultDET = sBuilderDET.toString();

				} catch (ClientProtocolException e5) {
					// TODO Auto-generated catch block
					e5.printStackTrace();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			// Log.v("JSON",httpEntity.getContent().toString());
			// Read content & Log
			CategoriaDataSource data = new CategoriaDataSource(a);
			data.open();
			// if(data.getCategoria(id))
			// data.deleteCategorie();
			ProdottoDataSource dataPr = new ProdottoDataSource(a);
			dataPr.open();
			DoveSiamoDataSource dataDS = new DoveSiamoDataSource(a);
			dataDS.open();
			dataDS.deleteDoveSiamoAll();
			ChiSiamoDataSource dataCS = new ChiSiamoDataSource(a);
			dataCS.open();
			dataCS.deleteChiSiamoAll();
			if (dataPer.isStarted()) {

				// Convert response to string using String Builder

				// parse JSON data

				// dataPr.deleteProdotti();

				HashMap<Integer, String> catTemp = new HashMap();

				if (result != null && !result.isEmpty()) {
					JSONArray jArray = null;
					try {
						jArray = new JSONArray(result);
					} catch (JSONException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					for (int i = 0; i < jArray.length(); i++) {

						JSONObject jObject = null;
						int id = 0;
						String dataModWebS = null;
						try {
							jObject = jArray.getJSONObject(i);
							Log.v("JSON", "CATEGORIA:");
							id = jObject.getInt("id");
							Log.v("JSON", String.valueOf(jObject.getInt("id")));
							dataModWebS = jObject.getString("last_change");
						} catch (JSONException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}

						Categoria cat = data.getCategoria(Long.valueOf(id));
						if (cat != null) {
							Date dataModIn = null;
							Date dataModWeb = null;
							try {
								dataModIn = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(cat.getDataMod());
								dataModWeb = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(dataModWebS);
							} catch (ParseException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}

							if (dataModIn != null && dataModWeb != null && dataModIn.before(dataModWeb)) {
								data.deleteCategoriaFromId(Long.valueOf(id));
								String nome = "";
								String descrizione = "";
								try {
									nome = URLDecoder.decode(Html.fromHtml(jObject.getString("titolo")).toString(), "ISO-8859-1");
									Log.v("JSON", nome);
									descrizione = URLDecoder.decode(Html.fromHtml(jObject.getString("descr")).toString(), "ISO-8859-1");
									Log.v("JSON", descrizione);
								} catch (UnsupportedEncodingException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

								catTemp.put(id, nome);
								data.createCategoria(Long.valueOf(id), nome, descrizione);
							}
						} else {
							String nome = "";
							String descrizione = "";
							try {
								nome = URLDecoder.decode(Html.fromHtml(jObject.getString("titolo")).toString(), "ISO-8859-1");
								Log.v("JSON", nome);
								descrizione = URLDecoder.decode(Html.fromHtml(jObject.getString("descr")).toString(), "ISO-8859-1");
								Log.v("JSON", descrizione);
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

							catTemp.put(id, nome);
							data.createCategoria(Long.valueOf(id), nome, descrizione);
						}
						// String tab1_text = jObject.getString("tab1_text");
						// int active = jObject.getInt("active");
					} // End Loop
				}
				// System.out.println(result2);
				if (result2 != null && !result2.isEmpty()) {
					JSONArray jArray2 = null;
					try {
						jArray2 = new JSONArray(result2);
					} catch (JSONException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					for (int i = 0; i < jArray2.length(); i++) {
						JSONObject jObject = null;
						try {
							jObject = jArray2.getJSONObject(i);
						} catch (JSONException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}

						String nome = "";
						String descrizione = "";
						String imm = "";
						int cat = 0;
						String des_short = "";
						String dataModWebS = "";
						String id = "";
						try {
							id = URLDecoder.decode(Html.fromHtml(jObject.getString("id")).toString(), "ISO-8859-1");
							Log.v("JSON", id);
							nome = URLDecoder.decode(Html.fromHtml(jObject.getString("titolo")).toString(), "ISO-8859-1");
							Log.v("JSON", nome);
							descrizione = URLDecoder.decode(Html.fromHtml(jObject.getString("descr")).toString(), "ISO-8859-1");
							Log.v("JSON", descrizione);
							imm = URLDecoder.decode(Html.fromHtml(jObject.getString("img")).toString(), "ISO-8859-1");
							Log.v("JSON", descrizione);
							cat = jObject.getInt("categ");
							Log.v("JSON", descrizione);
							des_short = URLDecoder.decode(Html.fromHtml(jObject.getString("descr_short")).toString(), "ISO-8859-1");
							Log.v("JSON", descrizione);
							dataModWebS = jObject.getString("last_change");

						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						Log.v("JSON", "PRODOTTI:");
						try {
							Log.v("JSON", String.valueOf(jObject.getInt("id")));
							Log.v("JSON", jObject.getString("titolo"));
							Log.v("JSON", jObject.getString("descr_short"));
							Log.v("JSON", jObject.getString("descr"));
							Log.v("JSON", jObject.getString("img"));
							Log.v("JSON", jObject.getString("categ"));
						} catch (JSONException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}

						Prodotto pr = dataPr.getProdotto(Long.valueOf(id));
						Date dataModIn = null;
						Date dataModWeb = null;
						if (pr != null) {

							try {
								dataModIn = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(pr.getDataMod());
								dataModWeb = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(dataModWebS);
							} catch (ParseException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}

							if (dataModIn != null && dataModWeb != null && dataModIn.before(dataModWeb)) {
								dataPr.deleteProdottoFromId(Long.valueOf(id));
								dataPr.createProdotto(Long.parseLong(id), nome, descrizione, catTemp.get(cat), imm, des_short, null);
								String[] files = a.getFilesDir().getAbsoluteFile().list();
								for (String file : files) {
									try {
										if (file.equals(jObject.getString("img"))) {
											// found=true;
											a.deleteFile(file);
										}
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}

								}
								// if(!found){
								try {

									URL url = new URL(properties.getProperty("imageDirProp") + jObject.getString("img"));
									// URL url = new
									// URL("http://www.tempogara.it/arcobaleno/temp/immagini/"+jObject.getString("immagine"));
									// HttpURLConnection conn =
									// (HttpURLConnection) url.openConnection();
									// conn.setDoInput(true);
									// conn.connect();
									InputStream is = url.openStream();// conn.getInputStream();
									BitmapFactory.Options opt = getOptions(is, 500, 500);
									is.close();
									is = url.openStream();// conn.getInputStream();

									Bitmap bm = loadBitmap(is, 500, 500, opt);// decodeSampledBitmapFromStream(is,
									// 500,
									// 500);//BitmapFactory.decodeStream(is);
									// bm.recycle();
									// bm=null;
									FileOutputStream fos = a.openFileOutput(jObject.getString("img"), a.MODE_PRIVATE);
									ByteArrayOutputStream outstream = new ByteArrayOutputStream();
									bm.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
									byte[] byteArray = outstream.toByteArray();

									fos.write(byteArray);
									fos.close();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						} else {
							dataPr.createProdotto(Long.parseLong(id), nome, descrizione, catTemp.get(cat), imm, des_short, null);
							String[] files = a.getFilesDir().getAbsoluteFile().list();
							for (String file : files) {
								try {
									if (file.equals(jObject.getString("img"))) {
										// found=true;
										a.deleteFile(file);
									}
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}
							// if(!found){
							try {

								URL url = new URL(properties.getProperty("imageDirProp") + jObject.getString("img"));
								// URL url = new
								// URL("http://www.tempogara.it/arcobaleno/temp/immagini/"+jObject.getString("immagine"));
								// HttpURLConnection conn = (HttpURLConnection)
								// url.openConnection();
								// conn.setDoInput(true);
								// conn.connect();
								InputStream is = url.openStream();// conn.getInputStream();
								BitmapFactory.Options opt = getOptions(is, 500, 500);
								is.close();
								is = url.openStream();// conn.getInputStream();

								Bitmap bm = loadBitmap(is, 500, 500, opt);// decodeSampledBitmapFromStream(is,
								// 500,
								// 500);//BitmapFactory.decodeStream(is);
								// bm.recycle();
								// bm=null;
								FileOutputStream fos = a.openFileOutput(jObject.getString("img"), a.MODE_PRIVATE);
								ByteArrayOutputStream outstream = new ByteArrayOutputStream();
								bm.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
								byte[] byteArray = outstream.toByteArray();

								fos.write(byteArray);
								fos.close();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

						// dataPr.createProdotto(jObject.getString("titolo"),
						// jObject.getString("descr"),
						// catTemp.get(jObject.getInt("categ")),
						// jObject.getString("img"),jObject.getString("descr_short"));

						// if(dataModIn!=null && dataModWeb!=null &&
						// dataModIn.before(dataModWeb)){
						// String[] files =
						// a.getFilesDir().getAbsoluteFile().list();
						// for(String file : files){
						// if (file.equals(jObject.getString("img"))){
						// // found=true;
						// a.deleteFile(file);
						// }
						//
						// }
						// // if(!found){
						// try {
						//
						// URL url = new
						// URL(properties.getProperty("imageDirProp")+jObject.getString("img"));
						// // URL url = new
						// URL("http://www.tempogara.it/arcobaleno/temp/immagini/"+jObject.getString("immagine"));
						// // HttpURLConnection conn = (HttpURLConnection)
						// url.openConnection();
						// // conn.setDoInput(true);
						// // conn.connect();
						// InputStream is =
						// url.openStream();//conn.getInputStream();
						// BitmapFactory.Options opt = getOptions(is, 500, 500);
						// is.close();
						// is = url.openStream();//conn.getInputStream();
						//
						// Bitmap bm = loadBitmap(is, 500, 500,
						// opt);//decodeSampledBitmapFromStream(is, 500,
						// 500);//BitmapFactory.decodeStream(is);
						// // bm.recycle();
						// // bm=null;
						// FileOutputStream fos =
						// a.openFileOutput(jObject.getString("img"),
						// a.MODE_PRIVATE);
						// ByteArrayOutputStream outstream = new
						// ByteArrayOutputStream();
						// bm.compress(Bitmap.CompressFormat.JPEG, 100,
						// outstream);
						// byte[] byteArray = outstream.toByteArray();
						//
						// fos.write(byteArray);
						// fos.close();
						// } catch(Exception e) {
						// e.printStackTrace();
						// }
						// }
						// }else{
						//
						// }

						// String tab1_text = jObject.getString("tab1_text");
						// int active = jObject.getInt("active");
					}
				}
				if (resultDS != null && !resultDS.isEmpty()) {
					// JSONArray jArrayDS = new JSONArray(resultDS);
					JSONObject jObject = null;
					try {
						jObject = new JSONObject(resultDS);
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}// jArrayDS.getJSONObject(0);
					String indirizzo = "";
					String mail = "";
					String cell = "";
					String tel = "";
					String fax = "";
					String lat = "";
					String lon = "";
					try {
						indirizzo = URLDecoder.decode(Html.fromHtml(jObject.getString("indirizzo")).toString(), "ISO-8859-1");
						Log.v("JSON", indirizzo);
						mail = URLDecoder.decode(Html.fromHtml(jObject.getString("mail")).toString(), "ISO-8859-1");
						Log.v("JSON", mail);
						cell = URLDecoder.decode(Html.fromHtml(jObject.getString("cell")).toString(), "ISO-8859-1");
						Log.v("JSON", cell);
						tel = URLDecoder.decode(Html.fromHtml(jObject.getString("tel")).toString(), "ISO-8859-1");
						Log.v("JSON", tel);
						fax = URLDecoder.decode(Html.fromHtml(jObject.getString("fax")).toString(), "ISO-8859-1");
						Log.v("JSON", fax);
						lat = URLDecoder.decode(Html.fromHtml(jObject.getString("lat")).toString(), "ISO-8859-1");
						Log.v("JSON", lat);
						lon = URLDecoder.decode(Html.fromHtml(jObject.getString("long")).toString(), "ISO-8859-1");
						Log.v("JSON", lon);
						dataDS.createDoveSiamo(indirizzo, mail, cell, tel, fax, lat, lon);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (resultCS != null && !resultCS.isEmpty()) {
					// JSONArray jArrayCS = new JSONArray(resultCS);
					JSONObject jObjectCS = null;
					try {
						jObjectCS = new JSONObject(resultCS);
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}// jArrayCS.getJSONObject(0);
					String descr = "";

					try {
						descr = URLDecoder.decode(Html.fromHtml(jObjectCS.getString("chisiamo")).toString(), "ISO-8859-1");
						Log.v("JSON", descr);
						dataCS.createChiSiamo(descr);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				if (resultDET != null && !resultDET.isEmpty()) {

					JSONArray jArray = null;
					try {
						jArray = new JSONArray(resultDET);
					} catch (JSONException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					for (int i = 0; i < jArray.length(); i++) {

						JSONObject jObject = null;
						int id = 0;
						String dataModWebS = null;

						try {
							jObject = jArray.getJSONObject(i);
						} catch (JSONException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}

						int prod;
						String titolo = "";
						String specifica = "";
						String last_change = "";
						try {
							titolo = URLDecoder.decode(Html.fromHtml(jObject.getString("titolo")).toString(), "ISO-8859-1");
							Log.v("JSON", titolo);
							specifica = URLDecoder.decode(Html.fromHtml(jObject.getString("specifica")).toString(), "ISO-8859-1");
							prod = jObject.getInt("prod");
							last_change = jObject.getString("last_change");
							Prodotto pr = dataPr.getProdotto(Long.valueOf(prod));
							Date dataModIn = null;
							Date dataModWeb = null;
							if (pr != null) {

								// try {
								// dataModIn = new
								// SimpleDateFormat("yyyy-MM-dd hh:mm:ss",
								// Locale.ITALY).parse(pr.getDataMod());
								// dataModWeb = new
								// SimpleDateFormat("yyyy-MM-dd hh:mm:ss",
								// Locale.ITALY).parse(last_change);
								// } catch (ParseException e1) {
								// // TODO Auto-generated catch block
								// e1.printStackTrace();
								// }
								//
								// if (dataModIn != null && dataModWeb != null
								// && dataModIn.before(dataModWeb)) {
								String cat = pr.getCategoria();
								String des = pr.getDescrizione();
								String color = jObject.getString("colore");
								if (!titolo.equals("null")) {
									des += "<br/><b>" + titolo + ":</b><br/>" + specifica;
									String desh = pr.getDescrizioneShort();
									long idPr = pr.getId();
									String imm = pr.getImmagine();
									String nome = pr.getNome();
									dataPr.deleteProdottoFromId(Long.valueOf(prod));
									dataPr.createProdotto(idPr, nome, des, cat, imm, desh, null);
								}

								if (!color.equals("null")) {
									if (!colori.containsKey(String.valueOf(prod)))
										colori.put(String.valueOf(prod), color);
									else {
										String colors = colori.get(String.valueOf(prod));
										colors += ", " + color;
										colori.put(String.valueOf(prod), colors);
									}
								}

							}

							// dataCS.createChiSiamo(descr);
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					for (String key : colori.keySet()) {
						Prodotto pr = dataPr.getProdotto(Long.valueOf(Integer.valueOf(key)));
						Date dataModIn = null;
						Date dataModWeb = null;
						if (pr != null) {

							String cat = pr.getCategoria();
							String des = pr.getDescrizione();
							String desh = pr.getDescrizioneShort();
							long idPr = pr.getId();
							String imm = pr.getImmagine();
							String nome = pr.getNome();
							dataPr.deleteProdottoFromId(Long.valueOf(Integer.valueOf(key)));
							dataPr.createProdotto(idPr, nome, des, cat, imm, desh, colori.get(key));
						}
					}
				}

				if (resultDEL != null && !resultDEL.isEmpty()) {

					JSONArray jArray = null;
					try {
						jArray = new JSONArray(resultDEL);
					} catch (JSONException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					for (int i = 0; i < jArray.length(); i++) {

						JSONObject jObject = null;
						int id = 0;
						String dataModWebS = null;

						try {
							jObject = jArray.getJSONObject(i);
						} catch (JSONException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}

						String tab = "";
						int idDel;
						String last_change = "";
						try {
							tab = URLDecoder.decode(Html.fromHtml(jObject.getString("tab")).toString(), "ISO-8859-1");
							Log.v("JSON", tab);
							idDel = jObject.getInt("id");
							last_change = jObject.getString("last_change");
							if (tab.equals("gall_prodotti")) {
								Prodotto pr = dataPr.getProdotto(Long.valueOf(idDel));
								Date dataModIn = null;
								Date dataModWeb = null;
								if (pr != null) {

									try {
										dataModIn = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(pr.getDataMod());
										dataModWeb = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(last_change);
									} catch (ParseException e1) {
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}

									if (dataModIn != null && dataModWeb != null && dataModIn.before(dataModWeb))
										dataPr.deleteProdottoFromId(Long.valueOf(idDel));

								}
							} else if (tab.equals("gall_categorie")) {
								Categoria cat = data.getCategoria(Long.valueOf(idDel));
								Date dataModIn = null;
								Date dataModWeb = null;
								if (cat != null) {

									try {
										dataModIn = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(cat.getDataMod());
										dataModWeb = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(last_change);
									} catch (ParseException e1) {
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}

									if (dataModIn != null && dataModWeb != null && dataModIn.before(dataModWeb))
										data.deleteCategoriaFromId(Long.valueOf(idDel));

								}
							}

							// dataCS.createChiSiamo(descr);
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}

			} else {
				if (result != null && !result.isEmpty()) {
					JSONArray jArray = null;
					try {
						jArray = new JSONArray(result);
					} catch (JSONException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					for (int i = 0; i < jArray.length(); i++) {

						JSONObject jObject = null;
						int id = 0;
						String dataModWebS = null;
						try {
							jObject = jArray.getJSONObject(i);
							Log.v("JSON", "CATEGORIA:");
							id = jObject.getInt("id");
							Log.v("JSON", String.valueOf(jObject.getInt("id")));
							dataModWebS = jObject.getString("last_change");
						} catch (JSONException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}
						if (data.getCategoria(Long.valueOf(id)) == null) {
							Log.v("NUOVO", "NUOVO");
							dataPer.setShowDialog(true);
						}
					}
				}

				if (result2 != null && !result2.isEmpty()) {
					JSONArray jArray2 = null;
					try {
						jArray2 = new JSONArray(result2);
					} catch (JSONException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					for (int i = 0; i < jArray2.length(); i++) {
						JSONObject jObject = null;
						try {
							jObject = jArray2.getJSONObject(i);
						} catch (JSONException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}

						// String nome = "";
						// String descrizione = "";
						// String imm = "";
						// int cat = 0;
						// String des_short = "";
						// String dataModWebS = "";
						String id = "";
						try {
							id = URLDecoder.decode(Html.fromHtml(jObject.getString("id")).toString(), "ISO-8859-1");
							Log.v("JSON", id);
							// nome =
							// URLDecoder.decode(Html.fromHtml(jObject.getString("titolo")).toString(),
							// "ISO-8859-1");
							// Log.v("JSON", nome);
							// descrizione =
							// URLDecoder.decode(Html.fromHtml(jObject.getString("descr")).toString(),
							// "ISO-8859-1");
							// Log.v("JSON", descrizione);
							// imm =
							// URLDecoder.decode(Html.fromHtml(jObject.getString("img")).toString(),
							// "ISO-8859-1");
							// Log.v("JSON", descrizione);
							// cat = jObject.getInt("categ");
							// Log.v("JSON", descrizione);
							// des_short =
							// URLDecoder.decode(Html.fromHtml(jObject.getString("descr_short")).toString(),
							// "ISO-8859-1");
							// Log.v("JSON", descrizione);
							// dataModWebS = jObject.getString("last_change");

						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						// Log.v("JSON", "PRODOTTI:");
						// try {
						// Log.v("JSON", String.valueOf(jObject.getInt("id")));
						// Log.v("JSON", jObject.getString("titolo"));
						// Log.v("JSON", jObject.getString("descr_short"));
						// Log.v("JSON", jObject.getString("descr"));
						// Log.v("JSON", jObject.getString("img"));
						// Log.v("JSON", jObject.getString("categ"));
						// } catch (JSONException e2) {
						// // TODO Auto-generated catch block
						// e2.printStackTrace();
						// }

						if (dataPr.getProdotto(Long.valueOf(id)) == null) {
							Log.v("IN", "NUOVO");
							dataPer.setShowDialog(true);
						}
					}
				}
				if (resultDEL != null && !resultDEL.isEmpty()) {

					JSONArray jArray = null;
					try {
						jArray = new JSONArray(resultDEL);
					} catch (JSONException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					for (int i = 0; i < jArray.length(); i++) {

						JSONObject jObject = null;
						int id = 0;
						String dataModWebS = null;

						try {
							jObject = jArray.getJSONObject(i);
						} catch (JSONException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}

						String tab = "";
						int idDel;
						String last_change = "";
						try {
							tab = URLDecoder.decode(Html.fromHtml(jObject.getString("tab")).toString(), "ISO-8859-1");
							Log.v("JSON", tab);
							idDel = jObject.getInt("id");
							last_change = jObject.getString("last_change");
							if (tab.equals("gall_prodotti")) {
								Prodotto pr = dataPr.getProdotto(Long.valueOf(idDel));
								Date dataModIn = null;
								Date dataModWeb = null;
								if (pr != null) {

									try {
										dataModIn = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(pr.getDataMod());
										dataModWeb = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(last_change);
									} catch (ParseException e1) {
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}

									if (dataModIn != null && dataModWeb != null && dataModIn.before(dataModWeb)) {
										Log.v("IN", "NUOVO");
										dataPer.setShowDialog(true);
									}

								}
							} else if (tab.equals("gall_categorie")) {
								Categoria cat = data.getCategoria(Long.valueOf(idDel));
								Date dataModIn = null;
								Date dataModWeb = null;
								if (cat != null) {

									try {
										dataModIn = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(cat.getDataMod());
										dataModWeb = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(last_change);
									} catch (ParseException e1) {
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}

									if (dataModIn != null && dataModWeb != null && dataModIn.before(dataModWeb)) {
										Log.v("IN", "NUOVO");
										dataPer.setShowDialog(true);
									}

								}
							}

							// dataCS.createChiSiamo(descr);
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				if (resultDET != null && !resultDET.isEmpty()) {

					JSONArray jArray = null;
					try {
						jArray = new JSONArray(resultDET);
					} catch (JSONException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					for (int i = 0; i < jArray.length(); i++) {

						JSONObject jObject = null;
						int id = 0;
						String dataModWebS = null;

						try {
							jObject = jArray.getJSONObject(i);
						} catch (JSONException e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}

						int prod;
						String titolo = "";
						String specifica = "";
						String last_change = "";
						try {
							titolo = URLDecoder.decode(Html.fromHtml(jObject.getString("titolo")).toString(), "ISO-8859-1");
							Log.v("JSON", titolo);
							specifica = URLDecoder.decode(Html.fromHtml(jObject.getString("specifica")).toString(), "ISO-8859-1");
							prod = jObject.getInt("prod");
							last_change = jObject.getString("last_change");
							Prodotto pr = dataPr.getProdotto(Long.valueOf(prod));
							Date dataModIn = null;
							Date dataModWeb = null;
							if (pr != null) {

								try {
									dataModIn = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(pr.getDataMod());
									dataModWeb = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ITALY).parse(last_change);
								} catch (ParseException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}

								if (dataModIn != null && dataModWeb != null && dataModIn.before(dataModWeb)) {
									Log.v("IN", "NUOVO");
									dataPer.setShowDialog(true);
								}

							}

							// dataCS.createChiSiamo(descr);
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				if (resultDS != null && !resultDS.isEmpty()) {
					// JSONArray jArrayDS = new JSONArray(resultDS);
					JSONObject jObject = null;
					try {
						jObject = new JSONObject(resultDS);
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}// jArrayDS.getJSONObject(0);
					String indirizzo = "";
					String mail = "";
					String cell = "";
					String tel = "";
					String fax = "";
					String lat = "";
					String lon = "";
					try {
						indirizzo = URLDecoder.decode(Html.fromHtml(jObject.getString("indirizzo")).toString(), "ISO-8859-1");
						Log.v("JSON", indirizzo);
						mail = URLDecoder.decode(Html.fromHtml(jObject.getString("mail")).toString(), "ISO-8859-1");
						Log.v("JSON", mail);
						cell = URLDecoder.decode(Html.fromHtml(jObject.getString("cell")).toString(), "ISO-8859-1");
						Log.v("JSON", cell);
						tel = URLDecoder.decode(Html.fromHtml(jObject.getString("tel")).toString(), "ISO-8859-1");
						Log.v("JSON", tel);
						fax = URLDecoder.decode(Html.fromHtml(jObject.getString("fax")).toString(), "ISO-8859-1");
						Log.v("JSON", fax);
						lat = URLDecoder.decode(Html.fromHtml(jObject.getString("lat")).toString(), "ISO-8859-1");
						Log.v("JSON", lat);
						lon = URLDecoder.decode(Html.fromHtml(jObject.getString("long")).toString(), "ISO-8859-1");
						Log.v("JSON", lon);
						dataDS.createDoveSiamo(indirizzo, mail, cell, tel, fax, lat, lon);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (resultCS != null && !resultCS.isEmpty()) {
					// JSONArray jArrayCS = new JSONArray(resultCS);
					JSONObject jObjectCS = null;
					try {
						jObjectCS = new JSONObject(resultCS);
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}// jArrayCS.getJSONObject(0);
					String descr = "";

					try {
						descr = URLDecoder.decode(Html.fromHtml(jObjectCS.getString("chisiamo")).toString(), "ISO-8859-1");
						Log.v("JSON", descr);
						dataCS.createChiSiamo(descr);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				dataPer.setStarted(true);
			}
		}
		return null;
	}

	public static int getScale(int originalWidth, int originalHeight, final int requiredWidth, final int requiredHeight) {
		// a scale of 1 means the original dimensions
		// of the image are maintained
		int scale = 1;

		// calculate scale only if the height or width of
		// the image exceeds the required value.
		if ((originalWidth > requiredWidth) || (originalHeight > requiredHeight)) {
			// calculate scale with respect to
			// the smaller dimension
			if (originalWidth < originalHeight)
				scale = Math.round((float) originalWidth / requiredWidth);
			else
				scale = Math.round((float) originalHeight / requiredHeight);

		}

		return scale;
	}

	public static BitmapFactory.Options getOptions(InputStream is, int requiredWidth, int requiredHeight) {

		BitmapFactory.Options options = new BitmapFactory.Options();
		// setting inJustDecodeBounds to true
		// ensures that we are able to measure
		// the dimensions of the image,without
		// actually allocating it memory
		options.inJustDecodeBounds = true;

		// decode the file for measurement
		BitmapFactory.decodeStream(is, null, options);

		// obtain the inSampleSize for loading a
		// scaled down version of the image.
		// options.outWidth and options.outHeight
		// are the measured dimensions of the
		// original image
		options.inSampleSize = getScale(options.outWidth, options.outHeight, requiredWidth, requiredHeight);

		// set inJustDecodeBounds to false again
		// so that we can now actually allocate the
		// bitmap some memory
		options.inJustDecodeBounds = false;

		return options;

	}

	public Bitmap loadBitmap(InputStream is, int requiredWidth, int requiredHeight, BitmapFactory.Options options) {

		// BitmapFactory.Options options= getOptions(is,requiredWidth,
		// requiredHeight);
		return BitmapFactory.decodeStream(is, null, options);
		// return BitmapFactory.decodeFile(filePath,options);
	}

	protected void onPostExecute(Void v) {
		this.progressDialog.dismiss();
		DataAppPersistence appData = (DataAppPersistence) a.getApplication();
		if (appData.isShowDialog()) {
			// DialogInterface.OnClickListener dialogClickListener = new
			// DialogInterface.OnClickListener() {
			// public void onClick(DialogInterface dialog, int which) {
			// switch (which) {
			// case DialogInterface.BUTTON_POSITIVE:
			// MyAsyncTask task = new
			// MyAsyncTask("www.tempogara.it/arcobaleno/temp/catalogo.php?data=categorie",Main2Activity.this);
			// task.execute();
			// break;
			// case DialogInterface.BUTTON_NEGATIVE:
			// break;
			// }
			// }
			//
			// };
			//
			// AlertDialog.Builder builder = new AlertDialog.Builder(this);
			// b
			// builder.setMessage("Ci sono aggiornamenti nel catalogo. Aggiornare? (Si consiglia una connessione wi-fi)").setPositiveButton("Si",
			// dialogClickListener).setNegativeButton("No",
			// dialogClickListener).show();
			new AlertDialog.Builder(a).setTitle("Aggiorna").setMessage("Ci sono aggiornamenti nel catalogo. Aggiornare?").setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton("SI", new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int whichButton) {
					MyAsyncTask task = new MyAsyncTask("www.tempogara.it/arcobaleno/temp/catalogo.php?data=categorie", a);
					task.execute();
				}
			}).setNegativeButton("NO", null).show();

			appData.setShowDialog(false);
		} else {
			Toast.makeText(a, "Il tuo catalogo è aggiornato, complimenti!", Toast.LENGTH_LONG).show();
		}
		a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

	} // protected void onPostExecute(Void v)
}// class MyAsyncTask extends AsyncTask<String, String, Void>

